﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ComLib.ComFun
{
    public class DESCryptoService
    {
        private static DESCryptoServiceProvider DesCSP = new DESCryptoServiceProvider();

        /// <summary>
        /// 将明文加密成密文
        /// </summary>
        /// <param name="plaintext">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string plaintext)
        {
            MemoryStream ms = new MemoryStream();//先创建 一个内存流
            CryptoStream cryStream = new CryptoStream(ms, DesCSP.CreateEncryptor(), CryptoStreamMode.Write);//将内存流连接到加密转换流
            StreamWriter sw = new StreamWriter(cryStream);
            sw.WriteLine(plaintext);//将要加密的字符串写入加密转换流
            sw.Close();
            cryStream.Close();
            byte[] buffer = ms.ToArray();//将加密后的流转换为字节数组
            return Convert.ToBase64String(buffer);//将加密后的字节数组转换为字符串
        }

        public static string Deciphering(string ciphertext)
        {
            byte[] buffer = Convert.FromBase64String(ciphertext);
            MemoryStream ms = new MemoryStream(buffer);//将加密后的字节数据加入内存流中
            CryptoStream cryStream = new CryptoStream(ms, DesCSP.CreateDecryptor(), CryptoStreamMode.Read);//内存流连接到解密流中
            StreamReader sr = new StreamReader(cryStream);
            string plaintext = sr.ReadToEnd();//将解密流读取为字符串
            sr.Close();
            cryStream.Close();
            ms.Close();
            return plaintext;
        }
    }
}
